﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using GMap.NET;
using GMap.NET.MapProviders;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers;
using TaxiDispatchClient.Properties;
using Model;

namespace TaxiDispatchClient
{
    public partial class AddOrderForm : DevExpress.XtraEditors.XtraForm
    {
        public AddOrderForm()
        {
            InitializeComponent();
        }

        public AddOrderForm(OrderInfo order)
        {
            InitializeComponent();
            _orderInfo = order;
        }

        private OrderInfo _orderInfo;

        internal readonly GMapOverlay objects = new GMapOverlay("objects");
        private void AddOrderForm_Load(object sender, EventArgs e)
        {
            //Map
            double theCenterLat = Settings.Default.MainMapLat;
            double theCenterLng = Settings.Default.MainMapLng;

            MainMap.Manager.Mode = AccessMode.ServerAndCache;
            MainMap.MapProvider = GMapProviders.GoogleChinaMap;
             
            MainMap.Overlays.Add(objects);
             
            MainMap.MaxZoom = 18;
            MainMap.MinZoom = 6;

            MainMap.Zoom = 12;
            MainMap.Position = new PointLatLng(theCenterLat, theCenterLng);
            MainMap.DragButton = MouseButtons.Left;

            if (_orderInfo!=null)
            {
                lb_id.Text = _orderInfo.Id.ToString();
                lb_startLat.Text = _orderInfo.StartLat.ToString("f6");
                lb_startLng.Text = _orderInfo.StartLng.ToString("f6");
                lb_endLat.Text = _orderInfo.EndLat.ToString("f6");
                lb_endLng.Text = _orderInfo.EndLng.ToString("f6");
                textEdit_PassengerName.Text = _orderInfo.PassengerName;
                textEdit_PassengerPhoneNumber.Text = _orderInfo.PhoneNumber;
                lb_calltime.Text = _orderInfo.CallTime.ToString("MM月dd日 HH:mm:ss");

                btnEdt_DriverName.Enabled = true;
                btnEdit_Taxi.Enabled = true;

                _startMaker = new GMarkerGoogle(new PointLatLng(_orderInfo.StartLat,
                    _orderInfo.StartLng), GMarkerGoogleType.green);
                _startMaker.ToolTipText = "起点";                
                objects.Markers.Add(_startMaker);

                _endMaker = new GMarkerGoogle(new PointLatLng(_orderInfo.EndLat,
                    _orderInfo.EndLng), GMarkerGoogleType.red);
                _endMaker.ToolTipText = "终点";
                objects.Markers.Add(_endMaker);                 
                drawRote();
                MainMap.Position = new PointLatLng(_orderInfo.StartLat,_orderInfo.StartLng);

            }
        }

        private GMapMarker _startMaker;
        private GMapMarker _endMaker;
        private GMapMarker _currentMaker;
        private PointLatLng _tmpPonintLatLng;


        private void MainMap_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                _tmpPonintLatLng = MainMap.FromLocalToLatLng(e.X, e.Y);
                barButtonItem_addStartPostion.Enabled = (_startMaker == null);
                barButtonItem_addEndPostion.Enabled = (_endMaker == null);
                popupMenu_left.ShowPopup(Control.MousePosition);
                
            }
        }

        private void barButtonItem_AddStartPostion_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            _startMaker = new GMarkerGoogle(_tmpPonintLatLng, GMarkerGoogleType.green);
            _startMaker.ToolTipText = "起点";
            lb_startLng.Text = "经度：" + Math.Round(_startMaker.Position.Lat, 2) + "，纬度：" +
                                             Math.Round(_startMaker.Position.Lng);
            objects.Markers.Add(_startMaker);
            drawRote();
  
        }

        private void barButtonItem_AddEndPostion_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            _endMaker = new GMarkerGoogle(_tmpPonintLatLng, GMarkerGoogleType.red);
            _endMaker.ToolTipText = "终点";
            objects.Markers.Add(_endMaker);

            lb_endLng.Text = "经度：" + Math.Round(_endMaker.Position.Lat, 2) + "，纬度：" +
                                  Math.Round(_endMaker.Position.Lng);
            drawRote();
        }

        private void drawRote()
        {
            if (_startMaker != null && _endMaker != null)
            {
                objects.Routes.Clear();
                RoutingProvider rp = MainMap.MapProvider as RoutingProvider;
                MapRoute route = rp.GetRoute(_startMaker.Position, _endMaker.Position, false, false, (int)MainMap.Zoom);
                GMapRoute r = new GMapRoute(route.Points, route.Name);
                objects.Routes.Add(r);
                labelControl_routeInfo.Text = route.Name;
            }
            else
            {
                objects.Routes.Clear();
            }

        }

        private void MainMap_OnMarkerClick(GMapMarker item, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _currentMaker = item;
                popupMenu_Right.ShowPopup(Control.MousePosition);

            }
        }

        private void barButtonItem_deleteMaker_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            objects.Markers.Remove(_currentMaker);
            if (_currentMaker.ToolTipText == "起点")
            {
                _startMaker = null;
            }
            else
            {
                _endMaker = null;
            }
            drawRote();
        }

        private void btnEdt_DriverName_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DriverInfoForm form = new DriverInfoForm();
            form.ShowDialog();
            if (form.DialogResult==DialogResult.Cancel)
            {
                return;
            }
            DataRow row = form.gridView1.GetDataRow(form.gridView1.FocusedRowHandle);
            if (row!=null)
            {                
                string strCardId = row["CardId"].ToString();
                int driverId = int.Parse(row["Id"].ToString());
                string strName = row["Name"].ToString();
                string strPhoneNumber = row["PhoneNumber"].ToString();
                _orderInfo.DriverCardId = strCardId;
                _orderInfo.DriverId = driverId;
                _orderInfo.DriverName = strName;
                _orderInfo.DriverPhoneNumber = strPhoneNumber;
                btnEdt_DriverName.Text = strName;
            }
        }

        private void btnEdit_Taxi_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            TaxiListForm form = new TaxiListForm();
            form.ShowDialog();
            if (form.DialogResult == DialogResult.Cancel)
            {
                return;
            }
            DataRow row = form.gridView1.GetDataRow(form.gridView1.FocusedRowHandle);
            if (row!=null)
            {
                string strTaxiNo = row["TaxiNo"].ToString();
                string strPhone = row["PhoneNumber"].ToString();
                int taxiId = int.Parse(row["Id"].ToString());
                _orderInfo.CarNo = strTaxiNo;
                _orderInfo.CarId = taxiId;
                _orderInfo.CarPhoneNumber = strPhone;
                btnEdit_Taxi.Text = strTaxiNo;
            }
        }

        private void btn_submit_Click(object sender, EventArgs e)
        {
            btn_submit.Enabled = false;
            Thread t = new Thread(SubmitOrder){IsBackground = true};
            t.Start();
        }

        private void SubmitOrder()
        {
            _orderInfo.SubmitTime = DateTime.Now;
            int result = MainForm.PositionService.SubmitAnOrder(_orderInfo);
            switch (result)
            {
                case 0:
                    XtraMessageBox.Show("该订单在服务器内存中已清除，请核对！");
                    break;
                case 1:
                    XtraMessageBox.Show("该订单在数据库中更新失败，请核对！");
                    break;
                case 2:
                    //XtraMessageBox.Show("");//发送订单信息时异常
                    break;
                case 3:
                    XtraMessageBox.Show("订单提交成功");
                    DialogResult = DialogResult.Yes;
                    BeginInvoke(new MethodInvoker(() => Close()));                    
                    break;
            }
            BeginInvoke(new MethodInvoker(() =>btn_submit.Enabled=true));
        }

    }
}